package com.example.code2022;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: dangwen
 * @createDate: 2022/4/22
 * 15. 三数之和
 * 给你一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？请你找出所有和为 0 且不重复的三元组。
 */
public class P15 {
    public static void main(String[] args) {
        int[] nums = new int[]{-1,0,1,2,-1,-4};
        System.out.println(JSON.toJSONString(threeSum(nums)));
    }

    // for循环控制轮数，首尾双指针控制取值
    public static List<List<Integer>> threeSum(int[] nums){
        List<List<Integer>> resultList = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++){
            if (nums[i] > 0){
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1]){
                continue;
            }
            int curr = nums[i];
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right){

                if (curr + nums[left] + nums[right] == 0){
                    resultList.add(Arrays.asList(curr, nums[left], nums[right]));
                    left++;
                    right--;
                    while (left < right && nums[left] == nums[left+1]){
                        left++;
                    }
                    while (left < right && nums[right] == nums[right-1]){
                        right--;
                    }
                } else if (curr + nums[left] + nums[right] < 0){
                    left++;
                } else{
                    right--;
                }
            }
        }
        return resultList;
    }

}
